package jwanalytics.web.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpUtils {
	
	
	/**
	 * Method left at this class because cookies are set at the HTTP response for a page request. Called from session.
	 * Will add a cookie to this response. */
	public static void addCookie(String cookieName, String cookieValue, HttpServletResponse resp) {
		resp.addCookie(new Cookie(cookieName, cookieValue));
	}
	
	
	/**
	 * Searches a cookie by name on the list of cookies for a request.
	 * @return null if cookie not found.  Cookie otherwise.
	 */
	public static Cookie searchCookieFromRequest(HttpServletRequest req, String cookieName) {
		return searchCookie(req.getCookies(), cookieName);
	}	
	
	
	/** 
	 * Searches a cookie by name on an array of cookies.
	 * @return null if cookie not found.  Cookie otherwise.
	 */
	public static Cookie searchCookie(Cookie[] list, String cookieName) {
		//precondition.
		if (list == null) return null;
		//body.
		for (int i = 0; i < list.length; i++) { //Search cookies returned by browser.
			if (list[i].getName().equals(cookieName)) {
				return list[i];
			}
		}
		return null;
	}
	
	
}
